package com.dfrz.planeclub.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/**
 * @author PuXiaLing
 * @description: TODO
 * @date 2024/3/27 19:44
 */
@Configuration
public class LettuceRedisConfig {

    @Bean
    @Scope(value = "prototype")
    public GenericObjectPoolConfig redisPool() {
        return new GenericObjectPoolConfig();
    }

    @Bean
    public LettucePoolingClientConfiguration poolConfig(@Autowired GenericObjectPoolConfig redisPool) {
        return LettucePoolingClientConfiguration.builder().poolConfig(redisPool).build();
    }

    //连接池信息
    @Bean
    public RedisStandaloneConfiguration redisConfig() {
        return new RedisStandaloneConfiguration();
    }

    @Bean
    public LettuceConnectionFactory redisConnectionFactory(@Autowired RedisStandaloneConfiguration configuration, @Autowired LettucePoolingClientConfiguration poolConfig) {
        return new LettuceConnectionFactory(configuration, poolConfig);
    }

    //自定义一个RedisTemplate，设置序列化器，方便操作实例对象
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(@Autowired LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }

}


